#!/bin/sh

usage()
{
	echo "reconf-screen [OPTIONS]"
	echo
	echo "Options:"
	echo " -u|--unified               Show one desktop on all screens"
	echo " -r|--resolution 1024x768   Force a specific resolution"
	echo " --nodvi                    Disable DVI"
	echo " --nohdmi                   Disable HDMI"
	echo " --nodp                     Disable DP"
	echo " --novga                    Disable VGA"
	echo " --nolvds                   Disable LVDS"
	echo " -h|--help                  Show this help text"
}

unified=0
res=
nodvi=0
nohdmi=0
nodp=0
novga=0
nolvds=0

while [ $# -ne 0 ]; do
	case "$1" in
		--help|-h)
			usage
			exit 0
			;;
		--unified|-u)
			unified=1
			;;
		--resolution|-r)
			shift
			res="$1"
			;;
		--nodvi)
			nodvi=1
			;;
		--nohdmi)
			nohdmi=1
			;;
		--nodp)
			nodp=1
			;;
		--novga)
			novga=1
			;;
		--nolvds)
			nolvds=1
			;;
		*)
			echo "Unknown option: $1"
			exit 1
			;;
	esac
	shift
done
[ -n "$res" ] && res="--mode $res"


getconn()
{
	# Assumes there is only one of each connection type
	xrandr | grep -Exe '^'$1'[0-9\-]* connected.*$' | head -n1 | cut -d' ' -f1
}

getdisconn()
{
	# Assumes there is only one of each connection type
	xrandr | grep -Exe '^'$1'[0-9\-]* disconnected.*$' | head -n1 | cut -d' ' -f1
}

DVI="$(getconn DVI)"
DVI_DISCONN="$(getdisconn DVI)"
HDMI="$(getconn HDMI)"
HDMI_DISCONN="$(getdisconn HDMI)"
DP="$(getconn DP)"
DP_DISCONN="$(getdisconn DP)"
VGA="$(getconn VGA)"
VGA_DISCONN="$(getdisconn VGA)"
LVDS="$(getconn LVDS)"
LVDS_DISCONN="$(getdisconn LVDS)"

[ $nodvi -ne 0 ] && { OFF_DVI="$DVI"; ON_DVI=; } || { OFF_DVI=; ON_DVI="$DVI"; }
[ $nohdmi -ne 0 ] && { OFF_HDMI="$HDMI"; ON_HDMI=; } || { OFF_HDMI=; ON_HDMI="$HDMI"; }
[ $nodp -ne 0 ] && { OFF_DP="$DP"; ON_DP=; } || { OFF_DP=; ON_DP="$DP"; }
[ $novga -ne 0 ] && { OFF_VGA="$VGA"; ON_VGA=; } || { OFF_VGA=; ON_VGA="$VGA"; }
[ $nolvds -ne 0 ] && { OFF_LVDS="$LVDS"; ON_LVDS=; } || { OFF_LVDS=; ON_LVDS="$LVDS"; }

ALL="$LVDS $DVI $HDMI $DP $VGA"
ON_ALL="$ON_LVDS $ON_DVI $ON_HDMI $ON_DP $ON_VGA"
OFF_ALL="$OFF_LVDS $OFF_DVI $OFF_HDMI $OFF_DP $OFF_VGA"
ALL_DISCONN="$LVDS_DISCONN $DVI_DISCONN $HDMI_DISCONN $DP_DISCONN $VGA_DISCONN"


for out in $ALL; do
	xrandr --output $out --auto
done
for out in $OFF_ALL $ALL_DISCONN; do
	xrandr --output $out --off
done
last_out=
for out in $ON_ALL; do
	if [ -z "$last_out" -o $unified -ne 0 ]; then
		xrandr --output $out --pos 0x0 $res
	else
		xrandr --output $out --right-of $last_out $res
	fi
	last_out=$out
done
